package winOrDie.Net.Http.httpmsg;

import java.io.IOException;
import java.rmi.RemoteException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.rpc.ServiceException;
import javax.xml.transform.TransformerException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import winOrDie.Net.Http.ws.impl.FunctionsImpl;
import winOrDie.Net.Http.ws.impl.FunctionsImplServiceLocator;

public class WoD_HttpMessage {
	/**
	 * Funci�n de Logueo. 
	 * @param http_dst -> direcci�n ip o dns del servidor web
	 * @param http_port -> puerto del servidor web
	 * @param LoginName -> nombre de usuario
	 * @param Password -> contrase�a de usuario
	 * @return 'true' -> correcto, 'false' -> incorrecto.
	 * @throws Exception (HTTP Connection Error/XML Error)
	 */
	public static boolean DoLogin(String http_dst, String http_port, String LoginName, String Password) throws Exception
	{
		FunctionsImplServiceLocator functionsImplServiceLocator = new FunctionsImplServiceLocator();
		functionsImplServiceLocator.setFunctionsImplEndpointAddress("http://"+http_dst+":"+http_port+"/WoD_WebService/services/FunctionsImpl");
    	FunctionsImpl peticio;
    	
		try {
			peticio = functionsImplServiceLocator.getFunctionsImpl();
			Document XmlRequest = WoD_XmlParsing_Client.getLoginMsg(LoginName, Password);
			String xml_Get_Login_Msg = WoD_XmlParsing_Client.ParseXmlDocumentToString(XmlRequest);
	    	
			Document xml_Login_Response = WoD_XmlParsing_Client.ParseStringToXmlDocument(peticio.doLogin(xml_Get_Login_Msg));
			
			String prova = WoD_XmlParsing_Client.ParseXmlDocumentToString(xml_Login_Response);
			
			System.out.println(prova);
			
	    	if(WoD_TreatXml.getLoginResult(xml_Login_Response))
	    		return true;
	    	else
	    		return false;
	    	
		} catch (ServiceException e) {
			// TODO Auto-generated catch block	
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		}    	    	
	}
	/**
	 * Informar al servidor web de nueva partida.
	 * @param http_dst -> direcci�n ip o dns del servidor web
	 * @param http_port -> puerto del servidor web
	 * @param ServerName -> nombre del creador de la partida
	 * @param ServerIP -> ip del creador de la partida
	 * @param ServerPort -> puerto del creador de la partida
	 * @param GameTitle -> nombre de la partida
	 * @return GameID en caso de �xito. -1 en caso de fallo.
	 * @throws Exception (HTTP Connection Error/XML Error)
	 */
	public static String NewGame(String http_dst, String http_port, String ServerName, String ServerIP, String ServerPort, String GameTitle) throws Exception
	{
		WoD_InfoPartidasActuales wipa = new WoD_InfoPartidasActuales();
		wipa.setServerName(ServerName);
		wipa.setServerIP(ServerIP);
		wipa.setServerPort(ServerPort);
		wipa.setServerStatus("1");
		wipa.setGameTitle(GameTitle);			
		
		FunctionsImplServiceLocator functionsImplServiceLocator = new FunctionsImplServiceLocator();
		functionsImplServiceLocator.setFunctionsImplEndpointAddress("http://"+http_dst+":"+http_port+"/WoD_WebService/services/FunctionsImpl");
		
    	FunctionsImpl peticio;
    	
		try {
			peticio = functionsImplServiceLocator.getFunctionsImpl();
			Document xml_NewGameRequest = WoD_XmlParsing_Client.getNewGameMsg(wipa);
			String xml_New_Game_Msg = WoD_XmlParsing_Client.ParseXmlDocumentToString(xml_NewGameRequest);	    	
			String xml_NewGame_Response = peticio.setNuevaPartida(xml_New_Game_Msg);
			
			System.out.println("\n xml_New_Game_Msg: " + xml_New_Game_Msg);
			
			Document xml_NewGameResponse = WoD_XmlParsing_Client.ParseStringToXmlDocument(xml_NewGame_Response);
			
			
			return WoD_TreatXml.getNewGameResult(xml_NewGameResponse);			
				    	
		} catch (ServiceException e) {
			// TODO Auto-generated catch block	
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		}    	    	
	}
	/**
	 * Actualizaci�n de informaci�n de partida. 
	 * @param http_dst -> direcci�n ip o dns del servidor web
	 * @param http_port -> puerto del servidor web
	 * @param ServerName -> nombre del creador de la partida
	 * @param ServerIP -> ip del creador de la partida
	 * @param ServerPort -> puerto del creador de la partida
	 * @param GameID -> identificador de la partida (respuesta de 'NewGame')
	 * @param GameTitle -> nombre de la partida
	 * @param PlayerNames -> ArrayList tipo String. Lista de los jugadores actuales.
	 * @return GameID en caso de �xito. -1 en caso de fallo.
	 * @throws Exception (HTTP Connection Error/XML Error) 
	 */
	public static String UpdateGame(String http_dst, String http_port, String ServerName, String ServerIP, 
			String ServerPort, String ServerStatus, String GameID, String GameTitle, ArrayList<String> PlayerNames) throws Exception
	{
		WoD_InfoPartidasActuales wipa = new WoD_InfoPartidasActuales();
		wipa.setServerName(ServerName);
		wipa.setServerIP(ServerIP);
		wipa.setServerPort(ServerPort);
		wipa.setServerStatus(ServerStatus);
		wipa.setGameTitle(GameTitle);
		wipa.setJugadores(PlayerNames);
		wipa.setGameID(GameID);
		
		FunctionsImplServiceLocator functionsImplServiceLocator = new FunctionsImplServiceLocator();
		functionsImplServiceLocator.setFunctionsImplEndpointAddress("http://"+http_dst+":"+http_port+"/WoD_WebService/services/FunctionsImpl");
		
    	FunctionsImpl peticio;
    	
		try {
			peticio = functionsImplServiceLocator.getFunctionsImpl();
			Document xml_NewGameRequest = WoD_XmlParsing_Client.getUpdateGameMsg(wipa);
			String xml_New_Game_Msg = WoD_XmlParsing_Client.ParseXmlDocumentToString(xml_NewGameRequest);
			
			System.out.println("\n REQUEST: " + xml_New_Game_Msg);
			
			Document xml_NewGameResponse = WoD_XmlParsing_Client.ParseStringToXmlDocument(peticio.setDatosPartida(xml_New_Game_Msg));
			
			System.out.println("\nRESPONSE: " + WoD_XmlParsing_Client.ParseXmlDocumentToString(xml_NewGameResponse));
			
			return WoD_TreatXml.getUpdateGameResult(xml_NewGameResponse);			
				    	
		} catch (ServiceException e) {
			// TODO Auto-generated catch block	
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		}  	    		
		
	}
	/**
	 * 
	 * @param http_dst -> direcci�n ip o dns del servidor web
	 * @param http_port -> puerto del servidor web
	 * @param GameID -> identificador de la partida (respuesta de 'NewGame')
	 * @param Winner -> Ganador: 1(Piratas)/2(Capitan)
	 * @param Players -> ArrayList de los jugadores de la partida. Tipo WoD_InfoJugadores
	 * Clase 'WoD_InfoJugadores' formada por: 
	 * 		String PlayerName, String Role ("1":pirata/"2":capitan).
	 * 		+Getters/Setters.
	 * @return GameID en caso de �xito. -1 en caso de fallo.
	 * @throws Exception (HTTP Connection Error/XML Error)
	 */
	public static String SetStats(String http_dst, String http_port, String GameID, String Winner, ArrayList<WoD_InfoJugadoresPartida> Players) throws Exception
	{
		FunctionsImplServiceLocator functionsImplServiceLocator = new FunctionsImplServiceLocator();
		functionsImplServiceLocator.setFunctionsImplEndpointAddress("http://"+http_dst+":"+http_port+"/WoD_WebService/services/FunctionsImpl");
    	FunctionsImpl peticio;
    	
		try {
			peticio = functionsImplServiceLocator.getFunctionsImpl();
			Document XmlRequest = WoD_XmlParsing_Client.getStatsMsg(GameID, Winner, Players);
			String xml_Get_Stats_Msg = WoD_XmlParsing_Client.ParseXmlDocumentToString(XmlRequest);
	    	
			Document xml_GetStats_Result = WoD_XmlParsing_Client.ParseStringToXmlDocument(peticio.setStatsPartida(xml_Get_Stats_Msg));
			
			System.out.println("\nSTATS RESULT: " +  WoD_XmlParsing_Client.ParseXmlDocumentToString(xml_GetStats_Result));
			
			return WoD_TreatXml.getStatsGameResult(xml_GetStats_Result);	
	    	
		} catch (ServiceException e) {
			// TODO Auto-generated catch block	
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		}    	    	
		
		
	}
	/**
	 * @param http_dst -> direcci�n ip o dns del servidor web
	 * @param http_port -> puerto del servidor web
	 * @return ArrayList de cada partida en la que se puede acceder.
	 * Clase 'WoD_InfoPartidasActuales' formada por: 
	 * 		String ServerName, String ServerIP, String ServerPort, 
	 * 		String ServerStatus, String GameID, String GameTitle, String PlayersNumber.
	 * 		+Getters/Setters.
	 * @throws Exception (HTTP Connection Error/XML Error) 
	 */
	public static ArrayList<WoD_InfoPartidasActuales> GetCurrentGames(String http_dst, String http_port) throws Exception
	{
		FunctionsImplServiceLocator functionsImplServiceLocator = new FunctionsImplServiceLocator();
		functionsImplServiceLocator.setFunctionsImplEndpointAddress("http://"+http_dst+":"+http_port+"/WoD_WebService/services/FunctionsImpl");
    	FunctionsImpl peticio;
    	
		try {
			peticio = functionsImplServiceLocator.getFunctionsImpl();
			Document XmlRequest = WoD_XmlParsing_Client.getPartidasMsg();
			String xml_Get_Partidas_Actuales = WoD_XmlParsing_Client.ParseXmlDocumentToString(XmlRequest);
	    	
			System.out.println("\nGET STATS REQUEST: " + xml_Get_Partidas_Actuales);
			
	    	String xml_Result = peticio.getPartidasActuales(xml_Get_Partidas_Actuales);
	    	
	    	System.out.println("\nGET STATS RESPONSE: " + xml_Result);
	    	
	    	ArrayList<WoD_InfoPartidasActuales> wipa = WoD_TreatXml.getPartidasResult(WoD_XmlParsing_Client.ParseStringToXmlDocument(xml_Result));
	    	
//	    	for (WoD_InfoPartidasActuales woD_InfoPartidasActuales : wipa) {
//				System.out.println("\nGameID: " + woD_InfoPartidasActuales.getGameID());
//				System.out.println("\nGameTitle: " + woD_InfoPartidasActuales.getGameTitle());
//				System.out.println("\nServerIp: " + woD_InfoPartidasActuales.getServerIP());
//				System.out.println("\nServerPort: " + woD_InfoPartidasActuales.getServerPort());
//				System.out.println("\nServerStatus: " + woD_InfoPartidasActuales.getServerStatus());
//			}
	    	
	    	return wipa;
		} catch (ServiceException e) {
			// TODO Auto-generated catch block	
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		}      	
	}
	/**
	 * 
	 * @param http_dst
	 * @param http_port
	 * @param GameID
	 * @return
	 * @throws Exception
	 */
	public static WoD_InfoPartidasActuales GetCurrentPlayersOnGame(String http_dst, String http_port, String GameID) throws Exception
	{
		FunctionsImplServiceLocator functionsImplServiceLocator = new FunctionsImplServiceLocator();
		functionsImplServiceLocator.setFunctionsImplEndpointAddress("http://"+http_dst+":"+http_port+"/WoD_WebService/services/FunctionsImpl");
    	FunctionsImpl peticio;
    	
		try {
			peticio = functionsImplServiceLocator.getFunctionsImpl();
			Document XmlRequest = WoD_XmlParsing_Client.getPlayersNumberMsg(GameID);
			String xml_Get_Current_Players = WoD_XmlParsing_Client.ParseXmlDocumentToString(XmlRequest);
	    	
			System.out.println("\nGET STATS REQUEST: " + xml_Get_Current_Players);
			
	    	String xml_Result = peticio.getCurrentPlayersOnGame(xml_Get_Current_Players);
	    	
	    	System.out.println("\nGET STATS RESPONSE: " + xml_Result);
	    		    	
	    	return WoD_TreatXml.getPlayersNumberOnGame(WoD_XmlParsing_Client.ParseStringToXmlDocument(xml_Result));
	    	
		} catch (ServiceException e) {
			// TODO Auto-generated catch block	
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		}  
	}
	
	public static boolean CheckWebServerConnection(String http_dst, String http_port) throws Exception
	{
		FunctionsImplServiceLocator functionsImplServiceLocator = new FunctionsImplServiceLocator();
		functionsImplServiceLocator.setFunctionsImplEndpointAddress("http://"+http_dst+":"+http_port+"/WoD_WebService/services/FunctionsImpl");
    	FunctionsImpl peticio;
    	
		try {
			peticio = functionsImplServiceLocator.getFunctionsImpl();
			Document XmlRequest = WoD_XmlParsing_Client.getCheckConnectionMsg();
			String xml_Check_Connection = WoD_XmlParsing_Client.ParseXmlDocumentToString(XmlRequest);
	    	
			System.out.println("\nGET STATS REQUEST: " + xml_Check_Connection);
			
	    	String xml_Result = peticio.checkConnection(xml_Check_Connection);
	    	
	    	System.out.println("\nGET STATS RESPONSE: " + xml_Result);
	    		    	
	    	return WoD_TreatXml.getCheckConnectionResult(WoD_XmlParsing_Client.ParseStringToXmlDocument(xml_Result));
	    	
		} catch (ServiceException e) {
			// TODO Auto-generated catch block	
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("HTTP Connection Error. " + e.getMessage());
			throw exception;
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			Exception exception = new Exception("XML Error. " + e.getMessage());
			throw exception;
		}  
	}
}
